package com.xxx.client.android.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.ListView;
import android.widget.ViewFlipper;

import com.flurry.android.FlurryAgent;
import com.xxx.client.android.CustomApplication;
import com.xxx.client.android.R;
import com.xxx.client.android.adapter.PurpleAdapter;
import com.xxx.client.android.adapter.PurpleEntry;
import com.xxx.client.android.adapter.PurpleListener;
import com.xxx.client.android.adapter.SceneSmallAdapter;
import com.xxx.client.android.adapter.SeparatedListAdapter;
import com.xxx.client.android.api.WSError;
import com.xxx.client.android.api.XXXApi;
import com.xxx.client.android.api.impl.XXXApiImpl;
import com.xxx.client.android.api.util.Ksoap2Caller;
import com.xxx.client.android.util.Tool;
import com.xxx.client.android.widget.FailureBar;
import com.xxx.client.android.widget.ProgressBar;

/**
 * @author lqh251@gmail.com
 * @version 2011-6-28
 */
public class HomeActivity extends Activity {

	private ViewFlipper mViewFlipper;
	private Gallery mGallery;
	private ProgressBar mProgressBar;
	private FailureBar mFailureBar;
	private ListView mHomeListView;
	private PurpleAdapter mBrowsePurpleAdapter;
	private PurpleAdapter mPersonalCenterPurpleAdapter;
	private ArrayList<String> sceneFileNameList;

	private XXXApi server;
	private SharedPreferences settings;
	private String ip;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		server = new XXXApiImpl();
		settings = getSharedPreferences(CustomApplication.TAG, 0);
		ip = settings.getString("ip", getString(R.string.server_default));
		server.setIP(ip);

		mHomeListView = (ListView) findViewById(R.id.HomeListView);
		mGallery = (Gallery) findViewById(R.id.Gallery);
		mProgressBar = (ProgressBar) findViewById(R.id.ProgressBar);
		mFailureBar = (FailureBar) findViewById(R.id.FailureBar);
		mViewFlipper = (ViewFlipper) findViewById(R.id.ViewFlipper);

		registerForContextMenu(mHomeListView);

		new NewsTask().execute((Void) null);
	}

	@Override
	protected void onResume() {
		fillHomeListView();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		FlurryAgent.onEndSession(CustomApplication.getInstance());
		super.onDestroy();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle(getString(R.string.choose_erver));
		String[] ips = getResources().getStringArray(R.array.server_others);
		int i = 0;
		menu.add(0, ++i, Menu.NONE, getString(R.string.server_default));
		for (String string : ips) {
			menu.add(0, ++i, Menu.NONE, string);
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		ip = item.getTitle().toString();
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("ip", ip);
		editor.commit();
		server.setIP(ip);
		return super.onContextItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// support for search key
		if (keyCode == KeyEvent.KEYCODE_SEARCH) {
			mHomeListView.setSelection(1);
			PurpleEntry entry = (PurpleEntry) mHomeListView.getAdapter()
					.getItem(1);
			entry.getListener().performAction();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.home, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.about_menu_item:
			Tool.about(this);
			break;
		case R.id.refresh_menu_item:
			refresh();
			break;
		case R.id.feedback_menu_item:
			startActivity(new Intent(HomeActivity.this, FeedbackActivity.class));
			break;
		case R.id.exit_menu_item:
			Tool.exit(HomeActivity.this);
			break;
		default:
		}
		return super.onOptionsItemSelected(item);
	}

	public void refresh() {
		Ksoap2Caller.clearCache();
		CustomApplication.getInstance().getImageCache().clearImageCache();
		new NewsTask().execute((Void) null);
	}

	/**
	 * Fills ListView with clickable menu items
	 */
	private void fillHomeListView() {
		CustomApplication.log("HomeActivity.fillHomeListView");
		mBrowsePurpleAdapter = new PurpleAdapter(this);
		ArrayList<PurpleEntry> browseListEntry = new ArrayList<PurpleEntry>();

		mPersonalCenterPurpleAdapter = new PurpleAdapter(this);
		ArrayList<PurpleEntry> personalCenterListEntry = new ArrayList<PurpleEntry>();

		// BROWSE
		browseListEntry.add(new PurpleEntry(R.drawable.list_search,
				R.string.search, new PurpleListener() {
					@Override
					public void performAction() {
						SearchActivity.launch(HomeActivity.this, 0);
					}
				}));

		browseListEntry.add(new PurpleEntry(R.drawable.list_navi,
				R.string.navigation, new PurpleListener() {
					@Override
					public void performAction() {
						NavigationActivity.launch(HomeActivity.this);
					}
				}));

		browseListEntry.add(new PurpleEntry(R.drawable.list_marquee,
				R.string.marquee, new PurpleListener() {
					@Override
					public void performAction() {
						MarqueeListActivity.launch(HomeActivity.this);
					}
				}));

		// PersonalCenter
		personalCenterListEntry.add(new PurpleEntry(R.drawable.list_history,
				R.string.history, new PurpleListener() {
					@Override
					public void performAction() {
						HistoryListActivity.launch(HomeActivity.this);
					}
				}));

		personalCenterListEntry.add(new PurpleEntry(R.drawable.list_download,
				R.string.download_1, new PurpleListener() {
					@Override
					public void performAction() {
						if (Environment.getExternalStorageState().equals(
								Environment.MEDIA_MOUNTED)) {
							String path = Environment
									.getExternalStorageDirectory().getPath()
									+ File.separator
									+ CustomApplication.TAG
									+ File.separator
									+ "download"
									+ File.separator;
							File file = new File(path);
							if (!file.exists()) {
								file.mkdirs();
							}
							FileBrowserActivity.launch(HomeActivity.this, path);
						} else {
							Tool.messageBox(HomeActivity.this,
									getString(R.string.sdcard_error));
						}
					}
				}));

		// attach list data to adapters
		mBrowsePurpleAdapter.setList(browseListEntry);
		mPersonalCenterPurpleAdapter.setList(personalCenterListEntry);

		// separate adapters on one list
		SeparatedListAdapter separatedAdapter = new SeparatedListAdapter(this);
		separatedAdapter.addSection(getString(R.string.welcome),
				mBrowsePurpleAdapter);
		separatedAdapter.addSection(getString(R.string.personal_center),
				mPersonalCenterPurpleAdapter);

		mHomeListView.setAdapter(separatedAdapter);
		mHomeListView.setOnItemClickListener(mHomeItemClickListener);
	}

	/**
	 * Launches menu actions
	 */
	private OnItemClickListener mHomeItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int index, long time) {
			PurpleListener listener = ((PurpleEntry) adapterView.getAdapter()
					.getItem(index)).getListener();
			if (listener != null) {
				listener.performAction();
			}
		}

	};

	private class NewsTask extends AsyncTask<Void, WSError, List<String>> {

		@Override
		public void onPreExecute() {
			mViewFlipper.setDisplayedChild(0);
			mProgressBar.setText(R.string.loading_news);
			super.onPreExecute();
		}

		@Override
		public List<String> doInBackground(Void... params) {
			XXXApi server = new XXXApiImpl();
			sceneFileNameList = null;
			try {
				sceneFileNameList = (ArrayList<String>) server
						.getSceneFileNameList();
			} catch (WSError e) {
				publishProgress(e);
			}
			return sceneFileNameList;
		}

		@Override
		public void onPostExecute(List<String> sceneFileNameList) {

			if (sceneFileNameList != null && sceneFileNameList.size() > 0) {
				mViewFlipper.setDisplayedChild(1);
				SceneSmallAdapter imageNewsListAdapter = new SceneSmallAdapter(
						HomeActivity.this);
				imageNewsListAdapter.setList(sceneFileNameList);
				mGallery.setAdapter(imageNewsListAdapter);
				mGallery.setOnItemClickListener(mGalleryListener);
				mGallery.setSelection(sceneFileNameList.size() / 2, true); // animate
																			// to
																			// center
			} else {
				mViewFlipper.setDisplayedChild(2);
				mFailureBar.setOnRetryListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						new NewsTask().execute((Void) null);
					}

				});
				mFailureBar.setText(R.string.connection_fail);
			}
			super.onPostExecute(sceneFileNameList);
		}

		@Override
		protected void onProgressUpdate(WSError... values) {
			Tool.messageBox(HomeActivity.this, values[0].getMessage());
			super.onProgressUpdate(values);
		}
	}

	private OnItemClickListener mGalleryListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {
			Intent intent = new Intent(HomeActivity.this, SceneActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("sceneFileNameList", sceneFileNameList);
			bundle.putInt("position", position);
			intent.putExtras(bundle);
			startActivity(intent);
		}

	};

}